package com.zmn.oms.api.listener;

import com.alibaba.fastjson.JSON;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.cube.common.utils.CollectionUtil;
import com.zmn.manager.mq.annotation.AliyunMQHandler;
import com.zmn.manager.mq.annotation.AliyunMQListener;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.manager.utils.OmsMqTagConsts;
import com.zmn.oms.manager.utils.SpringBeanFactoryUtil;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.model.entity.work.OrderWorkLogChange;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.third.haobai.HaobaiConsts;
import com.zmn.oms.zmn.business.interfaces.open.OrderChangeNotifyService;
import com.zmn.oms.zmn.business.interfaces.order.OrderUploadIascBService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * 类描述：工单变化状态推送
 *
 * @author liuying
 * @date 2019/06/11 11:44
 */
@Slf4j
@AliyunMQListener(topic = "${spring.mq.topic.oms}")
@Component
public class OrderChangeListener {

    /**
     * 状态同步
     *
     * @param message
     */
    @AliyunMQHandler(tags = OmsMqTagConsts.ZMN_TOPIC_OMS_ORDER_WORK_SYNC_CHANGE_API)
    public void orderChange(String message) {
        try {
            log.info("#mq#order#syncchange#recive message:{}", message);
            OrderWorkLogChange orderWorkLogChange = JSON.parseObject(message, OrderWorkLogChange.class);


            OrderChangeNotifyService orderChangeNotifyService = OrderChangeNotifyFactory.getInstance(orderWorkLogChange);
            if (orderChangeNotifyService != null) {
                orderChangeNotifyService.notifyChange(orderWorkLogChange);
            }
            else {
                log.info("#mq#order#syncchange#recive No orderChangeNotifyService found！ message:{}", message);
            }

            // 号百渠道需要集中推完成或取消状态
            int channelId = Optional.ofNullable(orderWorkLogChange.getChannelId()).orElse(-1);
            if (HaobaiConsts.isHaobaiChannel(channelId)) {
                OrderChangeNotifyService haobaiNotifyService = SpringBeanFactoryUtil.getBean("haobaiNotifyService");
                haobaiNotifyService.notifyChange(orderWorkLogChange);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}
